#!/usr/bin/env python
import cPickle
import os
import time

inc = 7 # number of increments for incremental backup
user = os.environ['USER']
# source directory
sourceDir = '/home/%s' % user
# target directory
targetDir = '/media/4988841d-92d4-4837-9ab3-2cb1ce665d9e/Junior'
targetDisk = '/media/4988841d-92d4-4837-9ab3-2cb1ce665d9e'
if os.access(targetDir, os.W_OK) and os.access(targetDisk, os.W_OK):
  try:
    iBackupFile = open('%s/.iBackup' % os.environ['HOME'], 'r')
    dirnames = cPickle.load(iBackupFile)
    iBackupFile.close()
  except IOError:
    dirnames = []
  if len(dirnames) < inc:
    print 'Backuping files ...'
    dirname = '%s' % (time.strftime('m%md%dy%Y_%Hh%Mm%Ss'))
    os.mkdir('%s/%s' % (targetDisk,dirname) )
    dirnames.append(dirname)
    iBackupFile = open('%s/.iBackup' % os.environ['HOME'], 'w')
    cPickle.dump(dirnames, iBackupFile)
    iBackupFile.close()
    print dirnames
    os.system('rsync -v --progress --force --ignore-errors --delete --backup --backup-dir=%s/%s -a %s/ %s/' % (targetDisk,dirname,sourceDir,targetDir))
  else:
    print 'Remove first backup and backuping files ...'
    os.mkdir('%s/emptydir' % (sourceDir))
    os.system('rsync -a --delete %s/emptydir/ %s/%s/' % (sourceDir,targetDisk,dirnames[0]))
    os.rmdir('%s/%s' % (targetDisk,dirnames[0]))
    os.rmdir('%s/emptydir' % (sourceDir))
    dirnames.remove(dirnames[0])
    dirname = '%s' % (time.strftime('m%md%dy%Y_%Hh%Mm%Ss'))
    os.mkdir('%s/%s' % (targetDisk,dirname) )
    dirnames.append(dirname)
    iBackupFile = open('%s/.iBackup' % os.environ['HOME'], 'w')
    cPickle.dump(dirnames, iBackupFile)
    iBackupFile.close()
    print dirnames
    os.system('rsync -v --progress --force --ignore-errors --delete --backup --backup-dir=%s/%s -a %s/ %s/' % (targetDisk,dirname,sourceDir,targetDir))
else:
  print 'Access to target directory for backup (%s) is not allowed !!!' % targetDir
